import type { CompanyCurrentUserInfoResult } from "@/api/siderBar/model"
import { getMyGetuserinfo, postMyChangecompanyCompanyId } from "@/api/siderBar/my"
import { useAppStore } from "./app"
import { message } from "ant-design-vue"
import { getLogout } from "@/api/siderBar/home"

export const useUserStore = defineStore(getLsKey("user"), () => {
    const userInfo = ref<INullable<CompanyCurrentUserInfoResult>>(null)
    async function getUserInfo() {
        userInfo.value = await getMyGetuserinfo()
    }
    async function switchCompany(companyId: number) {
        const appStore = useAppStore()
        try {
            appStore.toggleLoading(true, "切换中...")
            await postMyChangecompanyCompanyId(companyId)
            appStore.toggleLoading(false)
            await getUserInfo()
            message.success("切换成功")
            reload()
        } catch (error) {
            appStore.toggleLoading(false)
            console.log("切换企业失败", error)
            message.error("切换企业失败")
        }
    }
    async function logout() {
        await getLogout()
        invalidate()
    }
    function invalidate() {
        userInfo.value = null
        removeStorageToken()
    }
    return {
        userInfo,
        getUserInfo,
        switchCompany,
        logout,
        invalidate
    }
}, {
    persist: true
})
